package HTTP

import (
	"SQL/FSDB"
	"net/http"
)

type objectInfo struct {
	Nickname string
	Icon     string
	Custom   string
}

func getObjectData(w http.ResponseWriter, req *http.Request) {

	var resCode = http.StatusOK
	var msg = ""
	var res interface{}
	defer func() {
		writeResult(w, resCode, msg, res)
	}()

	objectID := req.FormValue("objectID")

	ok := false
	if ok, resCode, msg = isArgsEmpty(objectID); ok {
		return
	}
	if ok, resCode, msg = isValidID(objectID, "ObjectID"); !ok {
		msg = mInvalidObjectID
		return
	}

	errCode, errMsg, objInfo := getObjInfoFromDB(objectID)
	msg = errMsg
	if errCode != Success {
		resCode = errCode
		return
	}
	res = objInfo
}

func getObjInfoFromDB(objectID string) (errCode int, errMsg string, infoRows interface{}) {

	objInfoSQL := `SELECT nickname,icon,custom 
					FROM objects 
					WHERE id = $1;`
	rows, err := FSDB.Query(objInfoSQL, objectID)
	defer rows.Close()
	if err != nil {
		return errDBExecFailed, err.Error(), nil
	}
	objInfoRows := make([]objectInfo, 0)
	for rows.Next() {
		var (
			nickname string
			icon     string
			custom   []byte
		)
		err := rows.Scan(&nickname, &icon, &custom)
		if err != nil {
			return errDBExecFailed, err.Error(), nil
		}
		info := objectInfo{nickname, icon, string(custom)}
		objInfoRows = append(objInfoRows, info)
	}
	return Success, "获取资料成功！", objInfoRows
}
